#!/usr/bin/python
# -*- coding: utf-8 -*-

import ujson
import requests


class CtmsApi(object):
    def __init__(self, user, password, url):
        self.user = user
        self.password = password
        self.url = url

    def __call__(self, path, params=None, body=None):
        token = self.generate_token()
        print('获取Token：', token)
        if not params:
            params = {'access_token': token}
        else:
            params['access_token'] = token
        resp = requests.post('%s%s' % (self.url, path), params=params, json=body, timeout=30)
        if resp.status_code == 200:
            result = resp.text
            if result:
                return ujson.loads(result)
        elif resp.status_code == 401:
            print('ctms token invalidate')
            return {'code': resp.status_code, 'message': '401 Forbidden'}
        else:
            print('ctms error with unknown code: %d' % resp.status_code)
            return {'code': resp.status_code, 'message': None}

    def generate_token(self):
        """
        生成token，token一般只需生成一次即可，有效期一年，
        之后每次获取到的token值均相同，除非使用刷新token接口，
        此处为方便，每次调用接口时都获取token，实际不建议这么做，
        如果对安全性要求比较高，可以每隔几小时刷新一次token，
        否则获取一次以后设置为常量即可
        """
        body = {
            'userName': self.user,
            'password': self.password
        }
        response = requests.post(url=self.url + '/user/generate_access_token/v2', json=body, timeout=30)
        if response.status_code != 200:
            return ''
        result = response.text
        if not result:
            return ''
        json_result = ujson.loads(result)
        data = json_result.get('data')
        if not data:
            return ''
        return data.get('accessToken')
